package com.loveyukari.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate redisTemplate;


    public Object get(String key){return redisTemplate.opsForValue().get(key);}

    public <T> T get(String key,Class<T> type){
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null){
            return null;
        }
        return (T)o;
    }

    public <T> T opt(String key,Class<T> type,T defaultValue){
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null){
            return defaultValue;
        } else {
            return (T)o;
        }
    }



    public void set(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }

    public void set(String key,Object value,long time,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value,time,timeUnit);
    }
    public void del(String key){
        redisTemplate.delete(key);
    }

    public void del(Collection<String> keys){
        redisTemplate.delete(keys);
    }

    public Set<String> keys(String key){
        return redisTemplate.keys(key);
    }

    public void setList(String key,Object value){
        redisTemplate.opsForList().leftPush(key,value);
    }
    public void setListAll(String key,List values){
        redisTemplate.opsForList().leftPushAll(key,values);
    }

    public <T> List<T> rangList(String key,Class<T> type){
        Long size = redisTemplate.opsForList().size(key);
        List<T> list = redisTemplate.opsForList().range(key, 0, size);
        return list;
    }

    public <T> T rangListOne(String key,Class<T> type){
        List<T> list = redisTemplate.opsForList().range(key, 0, 0);
        if (list.isEmpty()){
            return null;
        }
        return list.get(0);
    }

    public void trimList(String key,long start,long end){
        redisTemplate.opsForList().trim(key,start,end);
    }



    public <T> T popListOne(String key,Class<T> type){
        Long size = redisTemplate.opsForList().size(key);
        if (size > 0){
            Object result =  redisTemplate.opsForList().rightPop(key);
            return (T)result;
        }
        return null;

    }

    public Long listSize(String key){
        return redisTemplate.opsForList().size(key);
    }




}
